package com.cheung.leetcode.arr;

public class LC209 {

    public static int minSubArrayLen(int target, int[] nums) {
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int sum = nums[i];
            if (sum >= target) {
                min = 1;
            } else {
                for (int j = i + 1; j < nums.length; j++) {
                    sum += nums[j];
                    if (sum >= target) {
                        min = Math.min(min, j - i + 1);
                    }
                }
            }
        }

        return min == Integer.MAX_VALUE ? 0 : min;
    }


    public static int minSubArrayLenV2(int target, int[] nums) {
        int left = 0;
        int sum = 0;
        int min = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= target) {
                min = Math.min(min, right - left + 1);
                sum -= nums[left++];
            }
        }

        return min == Integer.MAX_VALUE ? 0 : min;
    }


    public static void main(String[] args) {
        System.out.println(minSubArrayLenV2(7, new int[]{2, 3, 1, 2, 4, 3}));
    }
}
